﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IWS.SiteManager.Core.Model;
using System.IO;

namespace IWS.SiteManager.Core
{
	public class InstallHelper
	{
		public void Install(SetupInformation info)
		{
			//if database doesn't exist, it creates new schema and initalized data. 
			DBFactory.CheckDatabaseVersion(info.DBConnectionString); 

			//setup membership
			DBFactory.InstallMembership(info.MembershipDBConnectionString);

			//write the db config
			WriteDBConfig(info);

			System.Web.HttpRuntime.UnloadAppDomain(); //shoudl force web.config reload.
		}
		public void SetupApplication(SetupInformation info)
		{
			// admin user
			System.Web.Security.Roles.CreateRole("Admins");
			System.Web.Security.Roles.CreateRole("Editors");

			System.Web.Security.MembershipCreateStatus status = System.Web.Security.MembershipCreateStatus.Success;

			//create the admin user;
			System.Web.Security.Membership.CreateUser(info.AdminUser, info.AdminPass, info.AdminEmail, null, null, true, out status);

			if (status == System.Web.Security.MembershipCreateStatus.Success)
			{
				var member = System.Web.Security.Membership.GetUser(info.AdminUser);
				if (member != null)
				{
					System.Web.Security.Roles.AddUserToRoles(info.AdminUser, new string[] { "Admins", "Editors" });
				}
			}

			//update settings
			Core.Model.SiteManagerDataContext db = new SiteManagerDataContext();
			var setting = db.Settings.Where(o => o.ID == Constants.SiteHostname).SingleOrDefault();
			if (setting == null)
			{
				setting = new Setting();
				setting.ID = Constants.SiteHostname;
				db.Settings.InsertOnSubmit(setting);
			}

			setting.Value = info.WebHost;
			db.SubmitChanges();
		}

		private void WriteDBConfig(SetupInformation info)
		{
			StringBuilder builder = new StringBuilder();

			builder.AppendLine("<connectionStrings>");
			builder.AppendLine("	<clear/>");
			builder.AppendLine("	<add name=\"SiteManagerDefault\"");
			builder.AppendLine("		connectionString=\"{0}\"");
			builder.AppendLine("		providerName=\"System.Data.SqlClient\" />");
			builder.AppendLine("	<add name=\"SiteManagerMembership\"");
			builder.AppendLine("		connectionString=\"{1}\"");
			builder.AppendLine("		providerName=\"System.Data.SqlClient\"/>");
			builder.AppendLine("</connectionStrings>");

			System.Web.HttpContext context = System.Web.HttpContext.Current;
			if (context != null && context.Server != null)
			{
				string file = context.Server.MapPath("~/db.config");
				File.WriteAllText(file, string.Format(builder.ToString(), info.DBConnectionString, info.MembershipDBConnectionString),Encoding.UTF8);
			}
		}

	}
}
